﻿using System;
using System.Collections.Generic;
using System.Text;
using FlexLib;
using System.IO;
using FlexLib.Plugins;

namespace FlexminHost
{
	public class PluginTransport
	{
		public static void UploadPlugins(SocketReader reader, SocketWriter writer)
		{
			BinaryWriter fileWriter;

			string packagePath = Path.GetTempFileName();
			try
			{
				fileWriter = new BinaryWriter(new FileStream(packagePath, FileMode.Create, FileAccess.Write));
			}
			catch
			{
				return;
			}

			try
			{
				int length = reader.ReadInt();
				byte[] bytes = reader.ReadBytes(length);

				fileWriter.Write(bytes);
				fileWriter.Close();

				PluginManager.HostInstance.Install(packagePath);

				writer.WriteInt(0);

			}
			catch (Exception ex)
			{
			}
		}

		public static void ListPlugins(ICollection<Plugin> plugins, SocketReader reader, SocketWriter writer)
		{
			try
			{
				string SendingData = "";

				SendingData += plugins.Count.ToString();
				SendingData += '\t';
				foreach (Plugin plugin in plugins)
					SendingData += plugin.Info.Name + "\t" + plugin.Info.DisplayName + "\t" + plugin.Info.PluginVersion.ToString() + "\t";

				writer.WriteString(SendingData);
			}
			catch
			{
				// TODO: Error handling
			}
		}

		public static void DownloadPlugins(SocketReader reader, SocketWriter writer)
		{
			try
			{
				string pluginName = reader.ReadString();

				string packagePath = PluginManager.HostInstance.GetModulePath(pluginName);
				packagePath += Path.DirectorySeparatorChar + pluginName + ".fpkg";

				BinaryReader fileReader = new BinaryReader(new FileStream(packagePath, FileMode.Open, FileAccess.Read));
				byte[] data = fileReader.ReadBytes((int)fileReader.BaseStream.Length);
				fileReader.Close();

				writer.WriteInt(data.Length);
				writer.WriteBytes(data);
			}
			catch (Exception ex)
			{
			}
		}
	}
}
